package com.hua.api.modules.pay.rest;


import cn.hutool.core.io.IoUtil;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.hua.api.core.framework.annotation.AnonymousAccess;
import com.hua.api.core.framework.annotation.TokenCheck;
import com.hua.api.core.framework.util.Result;
import com.hua.api.modules.pay.service.PayInfoService;
import com.hua.api.modules.pay.service.WechatPayInfoService;
import com.hua.api.modules.pay.service.dto.OrderInfoPayinfoDto;
import com.hua.api.modules.pay.util.WechatPayUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/payinfo")
public class WechatPayController {

    private final WechatPayUtil wechatPayUtil;

    private final WechatPayInfoService wechatPayInfoService;

    private final PayInfoService payInfoService;

    /**
     *
     * */
    @AnonymousAccess
    @PostMapping("/refund/{outTradeNo}")
    @TokenCheck(userAgent = "RefundoutTrade")
    public Result refund(@PathVariable String outTradeNo, @RequestBody OrderInfoPayinfoDto dto){
        return Result.of(payInfoService.payinfoRefundUseOutTradeNo(outTradeNo,dto));
    }

//    @AnonymousAccess
//    @RequestMapping(value = "/wechat/notify/v3/order",method = RequestMethod.POST)
//    public ResponseEntity< Map<String,String>> wechatNotifyV3Order(@RequestBody String payNotifyForm,
//                                                             @RequestHeader("Wechatpay-Timestamp") String timestamp,
//                                                             @RequestHeader("Wechatpay-Nonce") String nonce,
//                                                             @RequestHeader("Wechatpay-Serial") String serial,
//                                                             @RequestHeader("Wechatpay-Signature") String signature
//    )

    @AnonymousAccess
    @RequestMapping(value = "/wechat/notify/v3/order",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Map<String,String>> notifyV3Order(HttpServletRequest request){
        log.info("微信支付回调信息： /wechat/notify/v3/order");
        try {
            String payNotifyForm = IoUtil.read(request.getInputStream(), Charset.forName("utf-8"));
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String serial = request.getHeader("Wechatpay-Serial");
            String signature = request.getHeader("Wechatpay-Signature");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                log.info("Header Name: " + headerName + ", Header Value: " + headerValue);
            }
            log.info("payNotifyForm={}",payNotifyForm);
            log.info("Wechatpay-Timestamp={}",timestamp);
            log.info("Wechatpay-Serial={}",serial);
            log.info("Wechatpay-Signature={}",signature);

            Map<String,String> resultMap = payInfoService.notifyV3Order(payNotifyForm,timestamp,serial,nonce,signature);
            return  new ResponseEntity<>(resultMap,HttpStatus.OK);
        } catch (Exception e) {
            // e.printStackTrace();
            log.warn("WxPayException e:"+e.getMessage());
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("code","FAIL");
            resultMap.put("message",e.getMessage());
            return   new ResponseEntity<>(resultMap,HttpStatus.BAD_REQUEST);
        }

    }


    /**
     * 微信退款
     * */
//    @AnonymousAccess
//    @PostMapping("/wechat/notify/v3/refunds")
//    public ResponseEntity<Map<String,String>>  wechatRefunds(@RequestBody String payNotifyForm,
//                                                     @RequestHeader("Wechatpay-Timestamp") String timestamp,
//                                                     @RequestHeader("Wechatpay-Nonce") String nonce,
//                                                     @RequestHeader("Wechatpay-Serial") String serial,
//                                                     @RequestHeader("Wechatpay-Signature") String signature){

        @AnonymousAccess
        @ResponseBody
        @RequestMapping(value = "/wechat/notify/v3/refunds",method = RequestMethod.POST)
        public ResponseEntity< Map<String,String>> refunds(HttpServletRequest request){
        log.info("微信退款回调信息： /notify/v3/refunds");
        try {
            String payNotifyForm = IoUtil.read(request.getInputStream(), Charset.forName("utf-8"));
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String serial = request.getHeader("Wechatpay-Serial");
            String signature = request.getHeader("Wechatpay-Signature");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                log.info("Header Name: " + headerName + ", Header Value: " + headerValue);
                // System.out.println("Header Name: " + headerName + ", Header Value: " + headerValue);
            }
            log.info("payNotifyForm={}",payNotifyForm);
            log.info("Wechatpay-Timestamp={}",timestamp);
            log.info("Wechatpay-Serial={}",serial);
            log.info("Wechatpay-Signature={}",signature);

            Map<String,String> resultMap = payInfoService.notifyV3Refund(payNotifyForm,timestamp,serial,nonce,signature);
            return  new ResponseEntity<>(resultMap,HttpStatus.OK);
        } catch (Exception e) {
            log.warn("WxPayException refunds e:"+e.getMessage());
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("code","FAIL");
            resultMap.put("message",e.getMessage());
            return new ResponseEntity<>(resultMap,HttpStatus.BAD_REQUEST);
        }

    }





}
